package com.elmcode.server.service.impl;

import com.elmcode.server.dto.FlavorDTO;
import com.elmcode.server.exception.FlavorException;
import com.elmcode.server.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elmcode.common.utils.PageUtils;
import com.elmcode.common.utils.Query;

import com.elmcode.server.dao.FlavorDao;
import com.elmcode.server.entity.FlavorEntity;


@Service("flavorService")
public class FlavorServiceImpl extends ServiceImpl<FlavorDao, FlavorEntity> implements FlavorService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FlavorEntity> page = this.page(
                new Query<FlavorEntity>().getPage(params),
                new QueryWrapper<FlavorEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateFlavor(Long id, FlavorDTO flavorDTO) {
        FlavorEntity flavorEntity = new FlavorEntity();
        flavorEntity.setId(id);
        BeanUtils.copyProperties(flavorDTO,flavorEntity);

        this.baseMapper.updateById(flavorEntity);
    }

    @Override
    public void saveFlavor(FlavorDTO flavorDTO){

        QueryWrapper<FlavorEntity> queryWrapper = new QueryWrapper<FlavorEntity>().eq("name",flavorDTO.getName());

        FlavorEntity entity = this.baseMapper.selectOne(queryWrapper);
        if(entity == null){
            FlavorEntity flavorEntity = new FlavorEntity();
            BeanUtils.copyProperties(flavorDTO,flavorEntity);

            this.baseMapper.insert(flavorEntity);
        }else {
            throw new FlavorException("当前口味已经存在，请重新输入");
        }
    }

}